import { UserService } from "@/services/userService";
import { loginModel } from "@/models/loginModel";
import { reactive, readonly } from 'vue'
export const useLoginStore = () => {
    const state = reactive({
        login: loginModel.create(),
    })
    const actions = {
        async login(packet) {
            const response = await UserService.loginUser(packet);
            //判断登录是否成功
            //检查返回信息中是否有error字段
            //如果有，则登录失败
            console.log(response);
            if (response.status == 200) {
                if (response.data.error) {
                    //登录失败
                    return false;
                }
                //登录成功
                state.login = loginModel.fromApi(response.data);
                localStorage.setItem("uuid", state.login.uuid);
                localStorage.setItem("name", state.login.name);
                localStorage.setItem("token", state.login.token);
                localStorage.setItem("permission", state.login.permission);
                localStorage.setItem("login", true);
            }
        },
        loadLogin() {
            state.login = loginModel.create();
            state.login.uuid = localStorage.getItem("uuid");
            state.login.name = localStorage.getItem("name");
            state.login.token = localStorage.getItem("token");
            state.login.permission = localStorage.getItem("permission");
            state.login.login = localStorage.getItem("login");
        }
    }
    return {
        state: readonly(state),
        actions
    }
}